package com.fh.Thread_Use;

import java.util.TimerTask;

/*
请编写程序，该程序可以每隔1秒。在控制台输出“hi！”，当输出10次后，自动退出。请使用实现Runnable接口的方式实现
*/
public class Thread02 {
    public static void main(String[] args) {
        MyThread02 myThread02 = new MyThread02();
//        myThread02.start();  这里会发现不能调用start
        //现在，创建Thread对象,把dog对象(实现Runnable)，放入Thread
        Thread thread = new Thread(myThread02);
        thread.start();
        Tiger tiger = new Tiger();
        ThreadProxy threadProxy = new ThreadProxy(tiger);
        threadProxy.start();
    }
}
class MyThread02 implements Runnable{
    int count = 0 ;
    @Override
    public void run() {
        while(true) {
            System.out.println("hi"+(++count)+Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (count ==10){
                break;
            }
        }
    }
}
//底层原理涉及到代理模式
class Animal{

}
class Tiger extends Animal implements Runnable{
    @Override
    public void run() {
        System.out.println("老虎嗷嗷叫");
    }
}
//线程代理类，模拟了一个极简的Thread类
class ThreadProxy implements Runnable{
    private Runnable target = null;
    @Override
    public void run() {
        if (target != null) {
            target.run();//动态绑定机制  (运行类型Tiger)
        }
    }
    public ThreadProxy(Runnable target) {
        this.target = target;
    }
    public void start(){
        start0();//这个方法才是真正多线程方法
    }
    public void start0(){
        run();
    }
}

